package ph.com.gs3.formalistics.presenter;

import java.util.ArrayList;
import java.util.List;

import ph.com.gs3.formalistics.ApplicationConfigs;
import ph.com.gs3.formalistics.R;
import ph.com.gs3.formalistics.global.constants.ActivityRequestCodes;
import ph.com.gs3.formalistics.global.constants.ActivityResultCodes;
import ph.com.gs3.formalistics.global.constants.DocumentFilter;
import ph.com.gs3.formalistics.global.constants.DocumentType;
import ph.com.gs3.formalistics.global.constants.StarMark;
import ph.com.gs3.formalistics.global.interfaces.CallbackCommand;
import ph.com.gs3.formalistics.global.utilities.logging.FLLogger;
import ph.com.gs3.formalistics.model.HttpCommunicator;
import ph.com.gs3.formalistics.model.facades.DocumentsDataReader;
import ph.com.gs3.formalistics.model.facades.OutgoingActionDataWriter;
import ph.com.gs3.formalistics.model.vo.business.User;
import ph.com.gs3.formalistics.model.vo.business.document.Document;
import ph.com.gs3.formalistics.model.vo.business.document.DocumentAction;
import ph.com.gs3.formalistics.model.vo.business.form.Form;
import ph.com.gs3.formalistics.model.vo.view.DocumentDisplayItem;
import ph.com.gs3.formalistics.model.vo.view.DocumentDisplayItem.TargetDocument;
import ph.com.gs3.formalistics.presenter.adapters.DocumentListItemViewAdapter;
import ph.com.gs3.formalistics.presenter.adapters.DocumentListItemViewAdapter.DocumentListItemActionListener;
import ph.com.gs3.formalistics.presenter.fragements.workers.MainWorkerFragment;
import ph.com.gs3.formalistics.presenter.fragments.views.DocumentListViewFragment;
import ph.com.gs3.formalistics.presenter.fragments.views.DocumentListViewFragment.DocumentListViewFragmentActionListener;
import ph.com.gs3.formalistics.presenter.fragments.views.MainViewFragment;
import ph.com.gs3.formalistics.presenter.fragments.views.MainViewFragment.MainViewActivityActionListener;
import ph.com.gs3.formalistics.services.DataSynchronizationService;
import ph.com.gs3.formalistics.services.broadcasters.Broadcaster;
import ph.com.gs3.formalistics.services.managers.DataSynchronizationManager.SyncType;
import ph.com.gs3.formalistics.services.managers.SessionManager;
import ph.com.gs3.formalistics.services.managers.SessionManager.CheckConnectionResult;
import ph.com.gs3.formalistics.services.managers.SessionManager.Mode;
import ph.com.gs3.formalistics.services.managers.SessionManager.SessionManagerEventListener;
import ph.com.gs3.formalistics.view.dialogs.FormSelectionDialogFragment;
import ph.com.gs3.formalistics.view.dialogs.FormSelectionDialogFragment.FormsAvailability;
import ph.com.gs3.formalistics.view.dialogs.ListSelectionDialogFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements MainViewActivityActionListener {

	public static final String TAG = MainActivity.class.getSimpleName();

	public static final String EXTRA_LOGGED_IN_USER = "current_user";

	// ========================================================================
	// {{ View Fields

	// View Fragments
	private MainViewFragment mainViewFragment;
	private DocumentListViewFragment homeViewFragment;
	private DocumentListViewFragment myWorkViewFragment;
	private DocumentListViewFragment myDocumentsViewFragment;
	private DocumentListViewFragment starredDocumentsViewFragment;
	private DocumentListViewFragment outboxDocumentViewFragment;

	// List Adapters For Views
	private DocumentListItemViewAdapter allDocumentsViewAdapter;
	private DocumentListItemViewAdapter myWorkDocumentsViewAdapter;
	private DocumentListItemViewAdapter myDocumentsViewAdapter;
	private DocumentListItemViewAdapter starredDocumentsViewAdapter;
	private DocumentListItemViewAdapter outboxDocumentsViewAdapter;

	private List<Fragment> documentListViewFragments = new ArrayList<>();

	// Worker Fragment(s)
	private MainWorkerFragment mainWorkerFragment;

	// Dialog(s)
	private FormSelectionDialogFragment formSelectionDialogFragment;

	// }}

	// ========================================================================
	// {{ Local State Fields
	private boolean formsAreCurrentlyUpdating = false;

	private Form currentFormFilter = null;

	// }}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		SessionManager sessionManager = SessionManager.getApplicationInstance();
		sessionManager.addListener(sessionManagerEventListener);

		if (savedInstanceState == null) {
			initializeWorkerFragment();
			initializeViewAdapters();
			refreshViewData(0);
			initializeDocumentListViewFragments();
			initializeMainViewFragment();
		}

		// Start the services once the view is ready
		registerBroadcastReceivers();
		startSyncAllService();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		Bundle extras = null;

		if (data != null) {
			extras = data.getExtras();
		}

		switch (resultCode) {
			case ActivityResultCodes.DOCUMENT_ACTION_SUBMITTED:
				startSendActionsSyncService();
				if (currentFormFilter == null) {
					refreshOutbox(0);
				} else {
					refreshOutbox(currentFormFilter.getId());
				}
				break;
			case ActivityResultCodes.DOCUMENT_STAR_MARKED:
				if (currentFormFilter != null) {
					refreshViewData(currentFormFilter.getId());
				} else {
					refreshViewData(0);
				}
				break;
			case ActivityResultCodes.LOGOUT_REQUESTED:
				if (extras != null) {
					if (extras.getInt(UserProfileActivity.EXTRA_LOGOUT_FLAG) == UserProfileActivity.FLAG_DID_LOGOUT) {
						mainWorkerFragment.logUserOut();
						returnToLoginActivity();
					}
				}
				break;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.

		switch (ApplicationConfigs.APPLICATION_MODE) {
			case DEVELOPMENT:
				getMenuInflater().inflate(R.menu.main_dev_mode, menu);
				break;
			case QA:
				getMenuInflater().inflate(R.menu.main_qa_mode, menu);
				break;
			case PRODUCTION:
				getMenuInflater().inflate(R.menu.main, menu);
				break;
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();

		switch (id) {
			case R.id.action_user_profile: {
				User currentUser = mainWorkerFragment.getCurrentUser();
				navigateToUserProfileView(currentUser);
			}
				break;
			case R.id.action_create_document: {
				openSelectFormDialogForDocumentCreation();
			}

				break;
			case R.id.action_logout: {
				mainWorkerFragment.logUserOut();
				returnToLoginActivity();
			}
				break;
			case R.id.action_open_tester: {
				Intent intent = new Intent(MainActivity.this, TesterActivity.class);
				startActivity(intent);
			}
				break;

		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterBroadcastReceivers();

		SessionManager sessionManager = SessionManager.getApplicationInstance();
		sessionManager.removeListener(sessionManagerEventListener);
	}

	// ========================================================================
	// {{ Initializers

	private void initializeWorkerFragment() {
		FragmentManager fragmentMan = getSupportFragmentManager();

		mainWorkerFragment = (MainWorkerFragment) fragmentMan
		        .findFragmentByTag(MainWorkerFragment.TAG);
		if (mainWorkerFragment == null) {
			// Initialize fields from extras
			Bundle extras = getIntent().getExtras();
			User currentUser = (User) extras.getSerializable(EXTRA_LOGGED_IN_USER);

			mainWorkerFragment = MainWorkerFragment.createInstance(currentUser);
			fragmentMan.beginTransaction().add(mainWorkerFragment, MainWorkerFragment.TAG).commit();
			fragmentMan.executePendingTransactions();
		}
	}

	private void initializeViewAdapters() {

		allDocumentsViewAdapter = new DocumentListItemViewAdapter(this);
		myWorkDocumentsViewAdapter = new DocumentListItemViewAdapter(this);
		myDocumentsViewAdapter = new DocumentListItemViewAdapter(this);
		starredDocumentsViewAdapter = new DocumentListItemViewAdapter(this);
		outboxDocumentsViewAdapter = new DocumentListItemViewAdapter(this);

		allDocumentsViewAdapter.setActionListener(documentListItemActionListener);
		myWorkDocumentsViewAdapter.setActionListener(documentListItemActionListener);
		myDocumentsViewAdapter.setActionListener(documentListItemActionListener);
		starredDocumentsViewAdapter.setActionListener(documentListItemActionListener);
		outboxDocumentsViewAdapter.setActionListener(documentListItemActionListener);

	}

	private void refreshViewData(int formId) {

		List<DocumentDisplayItem> allDS = mainWorkerFragment.getDocuments(formId,
		        DocumentFilter.ALL_DOCUMENTS);
		List<DocumentDisplayItem> forApprovalDS = mainWorkerFragment.getDocuments(formId,
		        DocumentFilter.MY_WORK);
		List<DocumentDisplayItem> ownDS = mainWorkerFragment.getDocuments(formId,
		        DocumentFilter.MY_DOCUMENTS);
		List<DocumentDisplayItem> starredDS = mainWorkerFragment.getDocuments(formId,
		        DocumentFilter.STARRED_DOCUMENTS);

		allDocumentsViewAdapter.setViewData(allDS);
		myWorkDocumentsViewAdapter.setViewData(forApprovalDS);
		myDocumentsViewAdapter.setViewData(ownDS);
		starredDocumentsViewAdapter.setViewData(starredDS);

		refreshOutbox(formId);
	}

	private void refreshOutbox(int formId) {
		List<DocumentDisplayItem> outgoingActions = mainWorkerFragment.getDocuments(formId,
		        DocumentFilter.OUTGOING_DOCUMENTS);
		outboxDocumentsViewAdapter.setViewData(outgoingActions);
	}

	/**
	 * Dependent to: initializeWorkerFragment(), initializeViewAdapters()
	 * 
	 */
	private void initializeDocumentListViewFragments() {
		// @formatter:off
		homeViewFragment 				= DocumentListViewFragment.createInstance("Home", allDocumentsViewAdapter);
		myWorkViewFragment 				= DocumentListViewFragment.createInstance("My Work", myWorkDocumentsViewAdapter);
		myDocumentsViewFragment 		= DocumentListViewFragment.createInstance("My Documents", myDocumentsViewAdapter);
		starredDocumentsViewFragment 	= DocumentListViewFragment.createInstance("Starred Documents", starredDocumentsViewAdapter);
		outboxDocumentViewFragment 		= DocumentListViewFragment.createInstance("Outbox", outboxDocumentsViewAdapter);
		// @formatter:on

		homeViewFragment.setActionListener(documentListViewFragmentActionListener);
		myWorkViewFragment.setActionListener(documentListViewFragmentActionListener);
		myDocumentsViewFragment.setActionListener(documentListViewFragmentActionListener);
		starredDocumentsViewFragment.setActionListener(documentListViewFragmentActionListener);
		outboxDocumentViewFragment.setActionListener(documentListViewFragmentActionListener);
	}

	/**
	 * Dependent to: initializeWorkerFragment(), initializeDocumentListViewFragments()
	 */
	private void initializeMainViewFragment() {
		FragmentManager fragmentMan = getSupportFragmentManager();

		List<Form> companyForms = mainWorkerFragment.getCurrentCompanyForms();

		documentListViewFragments.add((Fragment) homeViewFragment);
		documentListViewFragments.add((Fragment) myWorkViewFragment);
		documentListViewFragments.add((Fragment) myDocumentsViewFragment);
		documentListViewFragments.add((Fragment) starredDocumentsViewFragment);
		documentListViewFragments.add((Fragment) outboxDocumentViewFragment);

		mainViewFragment = MainViewFragment.createInstance(companyForms, documentListViewFragments,
		        SessionManager.getApplicationInstance().getMode());

		fragmentMan.beginTransaction().add(R.id.container, mainViewFragment).commit();
		fragmentMan.executePendingTransactions();

	}

	// }}

	// ========================================================================
	// {{ View Functional Methods

	private void resetFormFilters() {

		List<Form> forms = mainWorkerFragment.getCurrentCompanyForms();
		mainViewFragment.resetFormFilterSelection();
		mainViewFragment.addFormFilters(forms);

	}

	private void startSwipeRefresh() {
		for (Fragment fragment : documentListViewFragments) {
			((DocumentListViewFragment) fragment).startSwipeRefresh();
		}
	}

	private void stopSwipeRefresh() {
		for (Fragment fragment : documentListViewFragments) {
			((DocumentListViewFragment) fragment).stopSwipeRefresh();
		}
	}

	private void openSelectFormDialogForDocumentCreation() {

		if (formSelectionDialogFragment == null) {
			// lazy initialize the dialog fragment
			formSelectionDialogFragment = new FormSelectionDialogFragment();
		}

		if (formsAreCurrentlyUpdating) {
			// Forms are still updating
			formSelectionDialogFragment.setFormsAvailability(FormsAvailability.CURRENTLY_UPDATING);
		} else {

			// Update the form filter selection
			List<Form> companyForms = mainWorkerFragment.getCurrentCompanyForms();

			if (companyForms.size() >= 1) {
				formSelectionDialogFragment.setFormsAvailability(FormsAvailability.HAS_FORMS);
			} else {
				formSelectionDialogFragment
				        .setFormsAvailability(FormsAvailability.NO_FORMS_TO_SHOW);
			}
			formSelectionDialogFragment.setForms(companyForms);
		}

		formSelectionDialogFragment.show(getFragmentManager(), FormSelectionDialogFragment.TAG);
		formSelectionDialogFragment.setOnFormSelectedCallback(new CallbackCommand<Form>() {

			@Override
			public void execute(Form selectedForm) {
				navigateToDocumentView(DocumentType.NEW_DOCUMENT, selectedForm.getId(), 0);
			}
		});

	}

	private void showActionsDialogForDocument(int documentId) {

		String dialogHeader = "Actions";
		String dialogEmptyListMessage = "No are actions available for this document";

		ListSelectionDialogFragment dialog = new ListSelectionDialogFragment(dialogHeader,
		        dialogEmptyListMessage);

		DocumentsDataReader documentsDataReader = new DocumentsDataReader(this);
		final Document document = documentsDataReader.getDocument(documentId);

		List<DocumentAction> actions = document.getActions();

		List<String> actionStringList = new ArrayList<String>();

		for (DocumentAction action : actions) {
			actionStringList.add(action.getLabel());
		}

		dialog.setSelection(actionStringList);
		dialog.show(getFragmentManager(), ListSelectionDialogFragment.TAG);
		dialog.setOnItemSelectedCallback(new CallbackCommand<String>() {

			@Override
			public void execute(String result) {
				submitDocumentAction(document, result);
			}
		});

	}

	// }}

	// ========================================================================
	// {{ Functional Methods

	private void submitDocumentAction(Document document, String action) {

		OutgoingActionDataWriter outgoingActionDataWriter = new OutgoingActionDataWriter(this);
		outgoingActionDataWriter.saveDocumentAction(document.getId(), document.getFormId(),
		        document.getFieldValuesJSON(), action, mainWorkerFragment.getCurrentUser());

		startSendActionsSyncService();

		Toast.makeText(MainActivity.this,
		        "Action saved, your document will be updated after a while.", Toast.LENGTH_LONG)
		        .show();

		if (currentFormFilter == null) {
			refreshOutbox(0);
		} else {
			refreshOutbox(currentFormFilter.getId());
		}

	}

	// }}

	// ========================================================================
	// {{ Service Functional Methods

	private void registerBroadcastReceivers() {

		IntentFilter fullupdateIntentFilter = new IntentFilter();

		for (String action : Broadcaster.FULL_UPDATE_ACTIONS) {
			fullupdateIntentFilter.addAction(action);
		}

		fullupdateIntentFilter.addCategory(Intent.CATEGORY_DEFAULT);
		registerReceiver(dataSyncBroadcastReceiver, fullupdateIntentFilter);

		IntentFilter submitOutgoingActionIntentFilter = new IntentFilter();
		submitOutgoingActionIntentFilter.addAction(Broadcaster.OUGTOING_ACTIONS_SUBMITTED);
		submitOutgoingActionIntentFilter.addCategory(Intent.CATEGORY_DEFAULT);
		registerReceiver(outgoingActionsBroadcastReceiver, submitOutgoingActionIntentFilter);

	}

	private void unregisterBroadcastReceivers() {
		unregisterReceiver(dataSyncBroadcastReceiver);
		unregisterReceiver(outgoingActionsBroadcastReceiver);
	}

	private void startSyncAllService() {

		Intent intent = new Intent(this, DataSynchronizationService.class);
		intent.putExtra(DataSynchronizationService.EXTRA_SYNC_TYPE, SyncType.FULL_SYNC);
		startService(intent);

		startSwipeRefresh();

	}

	private void startSendActionsSyncService() {

		Intent intent = new Intent(this, DataSynchronizationService.class);
		intent.putExtra(DataSynchronizationService.EXTRA_SYNC_TYPE, SyncType.SEND_ACTIONS);
		startService(intent);

		startSwipeRefresh();

	}

	// }}

	// ========================================================================
	// {{ Navigation Functional Methods

	private void returnToLoginActivity() {

		FLLogger.d(TAG, "returnToLoginActivity");

		Intent intent = new Intent(MainActivity.this, LoginActivity.class);
		startActivity(intent);
		finish();

	}

	private void navigateToUserProfileView(User user) {

		Intent intent = new Intent(MainActivity.this, UserProfileActivity.class);
		intent.putExtra(UserProfileActivity.EXTRA_USER, user);
		startActivityForResult(intent, ActivityRequestCodes.WAIT_FOR_LOGOUT);

	}

	private void navigateToDocumentView(DocumentType documentType, int formId, int documentId) {

		User currentlyActiveUser = mainWorkerFragment.getCurrentUser();

		Intent documentActivity = new Intent(MainActivity.this, DocumentActivity.class);

		documentActivity.putExtra(DocumentActivity.EXTRA_CURRENT_USER, currentlyActiveUser);
		documentActivity.putExtra(DocumentActivity.EXTRA_DOCUMENT_TYPE, documentType);
		documentActivity.putExtra(DocumentActivity.EXTRA_FORM_ID, formId);
		documentActivity.putExtra(DocumentActivity.EXTRA_DOCUMENT_ID, documentId);

		startActivityForResult(documentActivity, ActivityRequestCodes.OPEN_DOCUMENT);

	}

	private void navigateToCommentsView(int documentId) {

		User currentlyActiveUser = mainWorkerFragment.getCurrentUser();

		Intent commentsActivity = new Intent(MainActivity.this, CommentsActivity.class);

		commentsActivity.putExtra(CommentsActivity.EXTRA_CURRENT_USER, currentlyActiveUser);
		commentsActivity.putExtra(CommentsActivity.EXTRA_CURRENT_DOCUMENT_ID, documentId);

		startActivity(commentsActivity);

	}

	// }}

	// ========================================================================
	// {{ Broadcast Receivers

	private BroadcastReceiver outgoingActionsBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (Broadcaster.OUGTOING_ACTIONS_SUBMITTED.equals(action)) {
				// TODO: refresh outgoing actions here
				startSyncAllService();
			}
		}

	};

	private BroadcastReceiver dataSyncBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			String action = intent.getAction();
			FLLogger.d(TAG, action); // TODO: remove this later

			if (Broadcaster.REAUTHENTICATION_REQUIRED.equals(action)) {
				returnToLoginActivity();
			}

			if (Broadcaster.FULL_UPDATE_DONE.equals(action)) {
				FLLogger.d(TAG, "Update done");
				stopSwipeRefresh();
			}

			if (Broadcaster.FULL_UPDATE_NOT_STARTED.equals(action)) {
				String message = intent.getStringExtra(Broadcaster.EXTRA_MESSAGE);
				FLLogger.d(TAG, message);
				stopSwipeRefresh();
			}

			if (Broadcaster.FORMS_SYNCHRONIZED.equals(action)) {
				resetFormFilters();
			}

			if (Broadcaster.OUGTOING_ACTIONS_SUBMITTED.equals(action)) {
				if (currentFormFilter == null) {
					refreshOutbox(0);
				} else {
					refreshOutbox(currentFormFilter.getId());
				}
			}

			if (Broadcaster.DOCUMENTS_PARTIALLY_SYNCHRONIZED.equals(action)) {
				if (currentFormFilter == null) {
					refreshViewData(0);
				} else {
					refreshViewData(currentFormFilter.getId());
				}
			}

		}

	};

	// }}

	private SessionManagerEventListener sessionManagerEventListener = new SessionManagerEventListener() {

		@Override
		public void onSessionLost() {
			mainViewFragment.notifyOfflineMode();
		}

		@Override
		public void onModeChanged(Mode mode) {
			if (mode == Mode.ONLINE) {
				mainViewFragment.notifyOnlineMode();
			} else {
				mainViewFragment.notifyOfflineMode();
				stopSwipeRefresh();
			}
		}
	};

	// ========================================================================
	// {{ View Implementation Methods

	@Override
	public void onFormFilterChanged(Form form) {
		currentFormFilter = form;
		refreshViewData(form.getId());
	}

	@Override
	public void onRetryConnectionRequested() {
		SessionManager sessionManager = SessionManager.getApplicationInstance();
		if (!sessionManager.isCurrentlyCheckingServerConnection()) {
			Toast.makeText(MainActivity.this, "Retrying connection", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(MainActivity.this, "Please wait", Toast.LENGTH_SHORT).show();
		}

		sessionManager.checkConnectionToServer(null,
		        new CallbackCommand<SessionManager.CheckConnectionResult>() {

			        @Override
			        public void execute(CheckConnectionResult result) {
				        if (result.connectionStatus == HttpCommunicator.STATUS_CONNECTED) {
					        startSyncAllService();
					        mainViewFragment.notifyOnlineMode();
				        } else {
					        mainViewFragment.notifyOfflineMode();
				        }
			        }
		        });
	}

	private DocumentListItemActionListener documentListItemActionListener = new DocumentListItemActionListener() {

		@Override
		public void onClickedDocumentActions(DocumentDisplayItem documentDisplayItem) {
			showActionsDialogForDocument(documentDisplayItem.getDocumentId());
		}

		@Override
		public void onDocumentStarMarked(DocumentDisplayItem documentDisplayItem,
		        StarMark newDocumentStar) {

			int documentId = documentDisplayItem.getDocumentId();
			int formId = documentDisplayItem.getFormId();

			mainWorkerFragment.changeDocumentStarMark(documentId, formId, newDocumentStar);

			// homeViewFragment.changeStarMark(id, newDocumentStar);
			// myWorkViewFragment.changeStarMark(id, newDocumentStar);
			// myDocumentsViewFragment.changeStarMark(id, newDocumentStar);
			// starredDocumentsViewFragment.changeStarMark(id, newDocumentStar);

			if (currentFormFilter != null) {
				refreshViewData(currentFormFilter.getId());
			} else {
				refreshViewData(0);
			}

			// TODO: refresh starredDocumentsViewFragment

		}

		@Override
		public void onClickedComments(DocumentDisplayItem documentDisplayItem) {
			navigateToCommentsView(documentDisplayItem.getDocumentId());
		}

	};

	private DocumentListViewFragmentActionListener documentListViewFragmentActionListener = new DocumentListViewFragmentActionListener() {

		@Override
		public void onRefreshCommand() {
			startSyncAllService();
		}

		@Override
		public void onDocumentSelected(DocumentDisplayItem document) {

			DocumentType documentType;

			if (document.getTargetDocument() == TargetDocument.ORIGINAL_DOCUMENT) {
				documentType = DocumentType.EXISTING_DOCUMENT;
			} else {
				documentType = DocumentType.OUTGOING_DOCUMENT;
			}

			navigateToDocumentView(documentType, document.getFormId(), document.getDocumentId());

		}

	};

	@Override
	public void onViewReady() {
		resetFormFilters();
	}

	// }}

}
